package cn.zfs.springcloud.datasource.contextholder;

import cn.zfs.springcloud.datasource.init.InitData;
import cn.zfs.springcloud.datasource.model.TransactionModel;

import java.util.ArrayList;
import java.util.List;

/**
 * 单个项目全局事务控制
 */
public class TransactionContextHolder {

    private final static ThreadLocal<List<TransactionModel>> TRANSACTION_MODEL_THREAD_LOCAL = new ThreadLocal<>();
    private final static ArrayList<TransactionModel> staticTransactionModels = new ArrayList<>(InitData.INITIALCAPACITY);

    public static void setTransactionModel(TransactionModel transactionModel){
        List<TransactionModel> transactionModels = TRANSACTION_MODEL_THREAD_LOCAL.get();
        if (transactionModels == null) {
            transactionModels = staticTransactionModels;
        }
        transactionModels.add(transactionModel);
        TRANSACTION_MODEL_THREAD_LOCAL.set(transactionModels);
    }

    public static List<TransactionModel> getTransactionModels() {
        return TRANSACTION_MODEL_THREAD_LOCAL.get();
    }

    public static void removeTransactionModel(){
        TRANSACTION_MODEL_THREAD_LOCAL.remove();
    }

}
